package com.example.android.commitcontent.ime.service;

import android.app.Service;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.example.android.commitcontent.ime.beans.HanZiWord;
import com.example.android.commitcontent.ime.beans.WordsUploadBody;
import com.example.android.commitcontent.ime.cores.utils.SPHelper;
import com.example.android.commitcontent.ime.database.hanzi.HanZiStatisticsDataBaseHelper;
import com.example.android.commitcontent.ime.database.managers.HanZiWordDictManager;

import java.util.ArrayList;
import java.util.List;

import cn.pluss.baselibrary.http.HttpRequest;
import cn.pluss.baselibrary.http.callback.SimpleHttpCallBack;
import cn.pluss.baselibrary.http.exception.ApiException;

public class CheckWordsDictUpdateService extends Service implements LifecycleOwner {

    private static final String KEY_WORD_DICT_AUTO_UPDATE_TIME = "word_dict_auto_update_time";
    private boolean isUpdating = false;

    public CheckWordsDictUpdateService() {
    }

    public static void start(Context context) {
        context.startService(new Intent(context, CheckWordsDictUpdateService.class));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isUpdating && isCanUpdate()) {
            isUpdating = true;
            uploadWordDict();
        }
        return super.onStartCommand(intent, flags, startId);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private boolean isCanUpdate() {
        long lastUpdateTime = SPHelper.get(this, KEY_WORD_DICT_AUTO_UPDATE_TIME, 0L);
        //更新频率24h
        long time = (System.currentTimeMillis() - lastUpdateTime) / 1000 / 60 / 60 / 24;
        return time >= 1;
    }


    /**
     * 上传词库
     */
    public void uploadWordDict() {
        List<HanZiWord> hanZiWordList = HanZiStatisticsDataBaseHelper.intance(this).getHanZiWordList();
        if (hanZiWordList.size() == 0) {
            updateWordDict();
            return;
        }
        HttpRequest.post("saveLexicon")
                .bindLifecycle(this)
                .execute(new WordsUploadBody(this, hanZiWordList), new SimpleHttpCallBack<String>() {

                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(String string) {
                        updateWordDict();
                    }

                    @Override
                    public void onError(ApiException e) {
                        isUpdating = false;
                    }

                    @Override
                    public void onCompleted() {
                    }
                });
    }

    /**
     * 更新词库
     */
    public void updateWordDict() {
        HttpRequest.post("queryLexicon")
                .bindLifecycle(this)
                .executeArray(HanZiWord.class, new SimpleHttpCallBack<HanZiWord>() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(ArrayList<HanZiWord> list) {
                        HanZiWordDictManager.instance(CheckWordsDictUpdateService.this).updateWordsDict(list, new HanZiWordDictManager.OnWordsUpdateSuccessListener() {
                            @Override
                            public void onWordsUpdateSuccess() {
                                SPHelper.put(CheckWordsDictUpdateService.this, KEY_WORD_DICT_AUTO_UPDATE_TIME, System.currentTimeMillis());
                                isUpdating = false;
                            }
                        });
                    }

                    @Override
                    public void onError(ApiException e) {
                        isUpdating = false;
                    }

                    @Override
                    public void onCompleted() {
                    }
                });
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return new Lifecycle() {
            @Override
            public void addObserver(@NonNull LifecycleObserver observer) {

            }

            @Override
            public void removeObserver(@NonNull LifecycleObserver observer) {

            }

            @NonNull
            @Override
            public State getCurrentState() {
                return State.RESUMED;
            }
        };
    }
}
